# -*- coding: utf-8 -*-
import bson
from flask import request, jsonify, g
from app.db.models.tasks import Task
from app.db.models.asset_tasks import AssetTasks
from app.db.models.siteportraits import SitePortRaits, SitePortRaitTask
from app.libs.redprint import RedPrint

api = RedPrint('site_portrait')


@api.route('/target_list', methods=['GET'])
def target_list():
    data = [
        {_.target: _.id}
        for _ in SitePortRaits.objects.filter(uid=g.user.id).only("id", "target").order_by("-updated_at")
    ]
    return jsonify({'code': 200, 'msg': 'ok', 'data': data})


@api.route('/target', methods=['GET'])
def target():
    data = {}
    request_args = request.args
    site_portrait_id = request_args.get('site_portrait_id', '')
    try:
        site_portrait_id = bson.ObjectId(site_portrait_id)
        site_portrait = SitePortRaits.objects.filter(pk=site_portrait_id, uid=g.user.id).first()
    except bson.errors.InvalidId:
        site_portrait = {}
    if not site_portrait:
        return jsonify({'code': 200, 'msg': 'ok', 'data': data})
    task_ids = AssetTasks.objects.filter(
            uid=g.user.id,
            targetUrl=site_portrait.target,
            taskGroupType="web_security",
            enableMonitor=True,
            vulSettings__enable=True,
            vulSettings__enableSitePortraitTriggerMonitor=True
        ).distinct("vulSettings.taskId")
    data["site_portrait"] = {
        "id": site_portrait.id,
        "portrait": site_portrait.portrait,
        "target": site_portrait.target,
        "version": site_portrait.version,
        "created_at": site_portrait.created_at,
        "updated_at": site_portrait.updated_at,
        "enable": bool(task_ids)
    }
    data["tasks"] = [
        {
            "id": task.id,
            "created_at": task.created_at,
            "patches": task.patches,
            "version": task.version,
        }
        for task in SitePortRaitTask.objects.filter(uid=g.user.id, target=site_portrait.target).order_by("-created_at").limit(20)
    ]
    task = Task.objects.filter(taskId__in=task_ids, status="completed").order_by("-endTime").first()
    data["warnings"] = []
    if task:
        data["warnings"] = [
            {
                "affects": _.affects,
                "title": _.title,
                "recommendation": _.recommendation,
                "impact": _.impact,
                "description": _.description,
                "reference": _.reference,
                "taskId": task.taskId,
                "warningId": _._id,
            }
            for _ in task.result.warnings
        ]
    return jsonify({'code': 200, 'msg': 'ok', 'data': data})
